import {
	storage
} from '@/utils/cache'
import Vue from 'vue'

let videoAd = qq.createRewardedVideoAd({
	adUnitId: '842d6982c2f159f9f1eb85cc40d3318d'
});

const types = {
	videoAd: 'videoAd',
	playState: 'playState', // 播放状态
	isOn: 'isOn', //是否已开始监控
	successFb: 'successFb', //成功观看回调函数
	failFb: 'failFb', //观看失败回调函数
}

const state = {
	[types.videoAd]: videoAd,
	[types.playState]: false,
	[types.isOn]: false,
	[types.successFb]: null,
	[types.failFb]: null,
}

const getters = {
	_videoAd(state) {
		return state[types.videoAd]
	}
}

const actions = {
	init: async ({
		commit,
		state
	}, {} = {}) => {
		if (!state[types.isOn]) {
			commit(types.isOn, true)
			state[types.videoAd].onError(res => {
				console.log('videoAd onError', res);
			});
			state[types.videoAd].onLoad(res => {
				commit(types.playState, true)
				console.log('videoAd onLoad', res);
			});
			state[types.videoAd].onClose(res => {
				if (res.isEnded) {
					if (state[types.playState]) {
						commit(types.playState, false)
						console.log('观看完成');
						setTimeout(()=>{
							state[types.successFb] && state[types.successFb]()
						},500)
					}
				} else {
					if (state[types.playState]) {
						commit(types.playState, false)
						console.log('观看失败')
						state[types.failFb] && state[types.failFb]()
					}
				}
			});
			console.info('init',state)
		}
		return state[types.videoAd]
	},
	show: async ({
		commit,
		state
	}, {success,fail} = {}) => {
		console.info('show',state)
		let isShow=false;
		if(state[types.isOn]){
			console.info('isOn',state)
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			commit(types.successFb, success)
			commit(types.failFb, fail)
			await state[types.videoAd]
				.load()
				.then(async () => {
					console.log('激励视频加载成功');
					await state[types.videoAd]
						.show()
						.then(() => {
							uni.hideLoading();
							isShow=true
							console.log('激励视频 广告显示成功');
						})
						.catch(err => {
							console.log('激励视频 广告显示失败');
						});
				})
				.catch(err => {
					console.log('激励视频加载失败');
				});	
		}
		return isShow
	},
}

const mutations = {
	[types.isOn]: (state, res) => {
		state[types.isOn] = res
	},
	[types.playState]: (state, res) => {
		state[types.playState] = res
	},
	[types.successFb]: (state, res) => {
		state[types.successFb] = res
	},
	[types.failFb]: (state, res) => {
		state[types.failFb] = res
	},
}

export default {
	namespaced: true,
	types,
	state,
	getters,
	actions,
	mutations
}
